package com.ruoyi.app.fragment

import android.app.Activity
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.ruoyi.app.activity.BaseVideoCallActivity
import com.ruoyi.app.activity.VideoCallSendActivity
import com.alick.learnwebrtc.adapter.ContactsAdapter
import com.alick.learnwebrtc.bean.Contact
import com.alick.learnwebrtc.bean.RoomBean
import com.alick.learnwebrtc.bean.request.GetAllContactRequest
import com.alick.learnwebrtc.http_api.ApiUtils
import com.alick.learnwebrtc.manager.WebSocketManager
import com.alick.learnwebrtc.manager.WebSocketManager.webSocketClient
import com.alick.learnwebrtc.utils.FilterUtils
import com.alick.learnwebrtc.utils.ToastUtils
import com.ruoyi.app.activity.AvatarActivity
import com.ruoyi.app.activity.MainActivity
import com.ruoyi.app.activity.SettingActivity
import com.ruoyi.app.activity.mine.EditInfoActivity
import com.ruoyi.app.activity.mine.InfoActivity
import com.ruoyi.app.adapter.NavigationAdapter
import com.ruoyi.app.databinding.ActivityContactsBinding
import com.ruoyi.app.databinding.FragmentContactsBinding
import com.ruoyi.app.model.Constant
import com.ruoyi.app.model.UserViewModel
import com.ruoyi.app.utils.CurrentInfo
import com.ruoyi.app.utils.LocalStorageUtils
import com.ruoyi.code.base.BaseBindingFragment
import com.ruoyi.code.base.activityViewModels
import org.java_websocket.handshake.ServerHandshake
import kotlin.getValue

class ContactsFragment : BaseBindingFragment<FragmentContactsBinding>() {

    companion object {
        @JvmStatic
        fun newInstance() = ContactsFragment()
    }

    private val viewModel: UserViewModel by activityViewModels()

    private val allContactsList: MutableList<Contact> by lazy {
        mutableListOf()
    }

    private val contactsAdapter: ContactsAdapter by lazy {
        ContactsAdapter(allContactsList)
    }
    private val webSocketListener = object : WebSocketManager.IWebSocketListener {
        override fun onOpen(serverHandshake: ServerHandshake) {
        }

        override fun onClose(code: Int, reason: String, remote: Boolean) {
            requireActivity().finish()
        }

        override fun onMessage(message: String) {
        }

        override fun onError(exception: Exception) {
            binding.swipeRefreshLayout.isRefreshing = false
        }
    }

    private val iContactsListener by lazy {
        object : WebSocketManager.IContactsListener {
            override fun onAdd(contact: Contact) {
                allContactsList.add(contact)
                requireActivity().runOnUiThread {
                    contactsAdapter.notifyDataSetChanged()
                }
            }

            override fun onRemove(contact: Contact) {
                FilterUtils.filterList(
                    allContactsList
                ) { model -> model.account == contact.account }
                requireActivity().runOnUiThread {
                    contactsAdapter.notifyDataSetChanged()
                }
            }

            override fun onGetAll(allContactList: MutableList<Contact>) {
                allContactsList.clear()
                FilterUtils.filterList(allContactsList){model -> model.account == LocalStorageUtils.getUserName() }
                allContactsList.addAll(allContactList)
                requireActivity().runOnUiThread {
                    contactsAdapter.notifyDataSetChanged()
                    binding.swipeRefreshLayout.isRefreshing = false
                }
            }
        }
    }

    override fun initView() {
        binding.rvContacts.layoutManager = LinearLayoutManager(requireActivity())
        binding.rvContacts.adapter = contactsAdapter

        contactsAdapter.onClickVideo = { contact ->
            activity?.let {
                val intent = Intent(it, VideoCallSendActivity::class.java)
                intent.putExtra(BaseVideoCallActivity.Companion.INTENT_KEY_TO_ACCOUNT, contact.account)
                startActivity(intent)
            }
        }


        WebSocketManager.addWebSocketListener(webSocketListener)
        WebSocketManager.addIContactsListener(iContactsListener)

        binding.swipeRefreshLayout.setOnRefreshListener {
            loadContacts()
        }

        binding.swipeRefreshLayout.isRefreshing = false
        loadContacts()


//        binding.ivAvatar.setOnClickListener {
//            AvatarActivity.startActivity(this.requireActivity())
//        }

//        binding.tvRoomList.setOnClickListener {
//            ApiUtils.Companion.requestGet<MutableList<RoomBean>>(ApiUtils.Companion.API_GET_ROOM_LIST,{
//                ToastUtils.show(it?.toString() ?:"无数据")
//            },{
//                ToastUtils.show(it)
//            })
//        }
    }

    override fun initData() {
//        TODO("Not yet implemented")
    }

    private fun loadContacts() {
        if(!WebSocketManager.hasInit){
            WebSocketManager.init(Constant.DEFAULT_INNER_ADDRESS, LocalStorageUtils.getUserName())
        }
        if(WebSocketManager.webSocketClient.isOpen){
            WebSocketManager.sendMsg(GetAllContactRequest())
        }else{
            WebSocketManager.connect()
            WebSocketManager.sendMsg(GetAllContactRequest())
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        WebSocketManager.removeIContactsListener(iContactsListener)
        WebSocketManager.removeWebSocketListener(webSocketListener)
    }
}